package com.zxy.supplier_system.server.service

import com.zxy.supplier_system.server.controller.GoodsController
import com.zxy.supplier_system.server.entity.SubGoods
import com.zxy.supplier_system.server.repository.GoodsRepository
import com.zxy.supplier_system.server.repository.SubGoodsRepository
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
class SubGoodsService(
    private val subGoodsRepository: SubGoodsRepository,
    private val goodsRepository: GoodsRepository,
    private val systemServiceService: SystemServiceService,
) {

    @Transactional
    fun importSubGoodsFromExcelItems(items: List<GoodsController.AddSubGoodsItem>): Int {
        val currentSystemService = systemServiceService.getCurrentSystemService()
        val goodsItems = items.distinctBy {
            it.barcode + it.number
        }.filter {
            goodsRepository.existsBySystemServiceAndBarcodeAndDisableIsFalse(currentSystemService, it.barcode)
                    &&
                    !subGoodsRepository.existsByNumberAndGoods_BarcodeAndGoods_SystemService(
                        it.number,
                        it.barcode,
                        currentSystemService
                    )
        }
        goodsItems.forEach {
            val goods = goodsRepository.findByBarcodeAndSystemServiceAndDisableIsFalse(it.barcode,currentSystemService)!!
            subGoodsRepository.save(SubGoods().apply {
                number = it.number
                this.goods = goods
                amount = it.amount
                name = it.name
            })
        }
        return goodsItems.size
    }

}